package com.zeng.sim.support.server.http;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Pair;
import com.zeng.sim.support.server.socket.ServerSimBusiProcessor;
import com.zeng.sim.util.SimConstant;
import com.zeng.sim.util.SysConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 报文模拟器-http服务端
 *
 * @author zengwanlin
 * @date 2023-12-25T17:31
 */
@RestController
@RequestMapping("/simulator")
public class ServerSimHttpController {

    @Autowired
    private ServerSimBusiProcessor serverSimBusiProcessor;

    @RequestMapping(value = "/request", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE,
            MediaType.TEXT_PLAIN_VALUE })
    public String request(HttpServletRequest request) {
        try {
            ServletInputStream inputStream = request.getInputStream();

            byte[] msgByte = IoUtil.readBytes(inputStream, false);
            String reqMsg = new String(msgByte,
                    SysConfigUtil.getSystemConfigValue(SysConfigUtil.CONFIG_CODE_SERVER_SIM_DEFAULT_CHARSET));
            Pair<String, String> pair = serverSimBusiProcessor.process(reqMsg);
            return pair.getValue();
        }
        catch (IOException e) {
            throw new IllegalStateException("处理请求失败，" + e.getMessage(), e);
        }
    }

    @RequestMapping(value = "/{channelNo}/{msgCode}")
    public String request(@PathVariable("channelNo") String channelNo, @PathVariable("msgCode") String msgCode) {
        Pair<String, String> pair = serverSimBusiProcessor.process(channelNo, msgCode);
        return pair.getValue();
    }

    @RequestMapping(value = "/{msgCode}")
    public String request(@PathVariable("msgCode") String msgCode) {
        return request(SimConstant.MSG_CHANNEL_NO_NONE, msgCode);
    }

}
